package net.hvacapp.cmvrfforandroid.db.dao.imp;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.db.dao.BaseDao;
import net.hvacapp.cmvrfforandroid.db.entity.Cache;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.utils.DateTimeUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.JSON.parseObject;

/**
 * 缓存的相关操作
 */
public class CacheDao extends BaseDao<Cache, Integer> {
    /**
     * Logger for this class
     */
    private Logger mLogger;
    private Cache mCache;

    public CacheDao(Context context) {
        super(context);
        mLogger = LoggerFactory.getLogger(CacheDao.class);
    }

    /**
     * 保存一条response记录，日期为自动获取值
     *
     * @param url        要保存的url
     * @param response   要保存的response
     * @param username   要保存的用户名
     * @param expireTime 过期时间，单位为小时
     */
    public void setResponse(String url, String username, long expireTime, String response) {
        if (TextUtils.isEmpty(response)) {
            return;
        }

		/*首先查找数据库，找出具有相同url和用户名的数据，删除掉*/
        Map<String, Object> equalFilter = new HashMap<String, Object>();
        equalFilter.put("url", checkURL(url));
        equalFilter.put("username", username.trim());
        List<Cache> datas = null;
        try {
            datas = find(equalFilter);
        } catch (Exception e) {
            e.printStackTrace();
            mLogger.info("setResponse() search record failed!!!");
        }
        if (datas != null
                && !datas.isEmpty()) {
            for (Cache item : datas) {
                delete(item);
            }
        }

        long curTime = DateTimeUtils.getSystemTime();

        mCache = new Cache();
        mCache.setDateTime(curTime + expireTime * 60 * 60 * 1000);
        mCache.setExpire(expireTime * 60 * 60 * 1000);
        mCache.setUrl(checkURL(url));
        mCache.setResponse(response.trim());
        mCache.setUsername(username.trim());
        try {
            insert(mCache);
        } catch (Exception e) {
            e.printStackTrace();
            mLogger.info("setResponse() insert record failed!!!");
        }
    }

    /**
     * 获取response字符串
     *
     * @param url
     * @param username
     * @return 返回Response字符串，如果没有查询到或者日期不一致，则返回null
     */
    @SuppressLint("SimpleDateFormat")
    public String getResponse(String url, String username) {

//        去掉缓存
        Map<String, Object> equalFilter = new HashMap<String, Object>();
        equalFilter.put("url", checkURL(url));
        equalFilter.put("username", username.trim());

        List<Cache> datas = null;
        try {
            datas = find(equalFilter);
        } catch (Exception e) {
            e.printStackTrace();
            mLogger.info("getResponse() search record failed!!!");
        }
        if (datas != null
                && !datas.isEmpty()) {
            long curTime = DateTimeUtils.getSystemTime();

            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String curDate = sDateFormat.format(new Date());
            Date dbDate = new Date(datas.get(0).getDateTime() - datas.get(0).getExpire());
            String recordDate = sDateFormat.format(dbDate);

			/*如果数据库中保存的失效时间大于系统时间，并且数据时同一天的。则缓存数据有效*/
            if (datas.get(0).getDateTime() > curTime
                    && (recordDate.compareTo(curDate) == 0)) {
                return datas.get(0).getResponse();
            } else {
                try {
                    deleteById(datas.get(0).getId());
                } catch (Exception e) {
                    e.printStackTrace();
                    mLogger.info("getResponse() delete record failed!!!");
                }
            }
        }
        return null;
    }

    /**
     * 保存一条response记录，日期为自动获取值
     *
     * @param url        要保存的url
     * @param param      请求中的参数字符串
     * @param response   要保存的response
     * @param username   要保存的用户名
     * @param expireTime 过期时间，单位为小时
     */
    public void setResponse(String url, String param, String username, long expireTime, String response) {
        StringBuilder newURL = new StringBuilder(url);
        newURL.append('?');
        newURL.append(param);
        setResponse(newURL.toString().trim(), username, expireTime, response);
    }

    /**
     * 把对象缓存起来
     * @param url 接口地址
     * @param username 用户名，可以传token
     * @param expireTime 过期时间
     * @param obj 保存对象
     * @return 缓存里数据是否和对象数据一样，返回false就是一样，可以不用刷新页面, 返回true，数据不一样，需要刷新
     */
    public boolean setResponse(String url, String username, long expireTime, Object obj) {
        boolean ret; //是否需要刷新
        String cacheStr = getResponse(url, username);
        String saveStr = JSON.toJSONString(obj);
        if (cacheStr != null && cacheStr.equals(saveStr)) {
            ret = false;
        }
        else {
            ret = true;
        }
        setResponse(url, username, expireTime, saveStr);
        return ret;
    }

    /**
     * 获取缓存数据对象
     * @param url 接口地址
     * @param username 用户名，可以传token
     * @param c 返回的对象model
     * @param <T>  返回的对象model
     * @return 返回对象数据
     */
    public <T> T getResponse(String url, String username, Class<T> c) {
        String ret = getResponse(url, username);
        if (StringUtils.isNotEmpty(ret)) {
            T obj = (T) parseObject(ret, c);
            return obj;
        }
        return null;
    }

    /**
     * 获取response字符串
     *
     * @param url
     * @param param
     * @param username
     * @return
     */
    public String getResponse(String url, String param, String username) {
        StringBuilder newURL = new StringBuilder(url);
        newURL.append('?');
        newURL.append(param);
        return getResponse(newURL.toString().trim(), username);
    }

    /**
     * 设置登录用户的相关信息
     *
     * @param uri
     * @param username
     * @param expireTime
     * @param info
     */
    public void SetUserInfo(String uri, String username, long expireTime, String info) {
        setResponse(uri, username, expireTime, info);
    }

    /**
     * 获得当前用户设置的信息
     *
     * @param uri
     * @param username
     * @return
     */
    public String GetUserInfo(String uri, String username) {
        return getResponse(uri, username);
    }

    /**
     * 去掉url字符串里的token相关的字符串
     *
     * @param url
     * @return
     */
    private String checkURL(String url) {
        String tokenStr = "?token=" + AccountManager.getInstance().getToken();
        String retStr = url.replace(tokenStr, "");
        return retStr.trim();
    }
}
